package com.lin.manager.login.service.impl;

import com.lin.manager.secure.model.SecurityUser;
import com.lin.manager.system.entity.SysRoleEntity;
import com.lin.manager.system.entity.SysUserEntity;
import com.lin.manager.system.service.SysRoleService;
import com.lin.manager.system.service.SysUserService;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author linjiang
 * @date 2024/7/25
 * @fn
 */
@Service
public class UserNameServiceImpl implements UserDetailsService {
    @Resource
    SysUserService userService;
    @Resource
    SysRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserEntity sysUser = userService.getByUsername(username);
        if (Objects.isNull(sysUser)) {
            throw new UsernameNotFoundException("账户或密码错误");
        }

        // 创建认证账户
        SecurityUser securityUser = createSecurityUser(sysUser);
        // 获取权限
        List<SysRoleEntity> roleList = roleService.findRoleByUserId(sysUser.getId().toString());
        Set<GrantedAuthority> auths = roleList.stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role)).collect(Collectors.toSet());
        securityUser.setAuthorities(auths);
        return securityUser;
    }

    /**
     * 构建安全用户
     *
     * @param sysUser
     * @return
     */
    private SecurityUser createSecurityUser(SysUserEntity sysUser) {
        Integer status = sysUser.getStatus();
        if (status.equals(1)) {
            throw new AccountExpiredException("账号已过期");
        }
        if (status.equals(2)) {
            throw new LockedException("账号已被锁定");
        }
        if (status.equals(3)) {
            throw new DisabledException("账号已禁用");
        }

        return SecurityUser.builder()
                .id(sysUser.getId())
                .name(sysUser.getName())
                .username(sysUser.getUsername())
                .phone(sysUser.getPhone())
                .status(sysUser.getStatus())
                .password(sysUser.getPassword())
                .build();
    }
}
